<template>
  <div id="container"></div>
</template>

<script setup>
import { onMounted, onUnmounted, defineProps, ref, watch } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

// 定义接收中心点的props
const props = defineProps({
  center: {
    type: Array,
    default: () => ref([118.186868, 24.475187])
  }
})

let map = null
let marker = null

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: '5aabd76db61a2972cf06e6fdb228a6f4'
  }
  AMapLoader.load({
    key: '24476c88646fc730e96da725bf1822c3',
    version: '2.0',
    plugins: ['AMap.Scale', 'AMap.Marker'] // 确保加载了 Marker 插件
  })
    .then((AMap) => {
      map = new AMap.Map('container', {
        viewMode: '3D',
        zoom: 11,
        center: props.center
      })
      // 创建点标记并添加到地图上
      marker = new AMap.Marker({
        position: props.center,
        map: map
      })
      console.log(props.center)
    })
    .catch((e) => {
      console.log(e)
    })
})

// 监听中心点变化并移动地图中心和点标记
watch(
  () => props.center.value,
  (newValue) => {
    if (map && marker) {
      map.setCenter(newValue)
      marker.setPosition(newValue)
    }
  }
)

onUnmounted(() => {
  if (marker) {
    marker.setMap(null)
  }
  map?.destroy()
})
// console.log(props.center.value)
</script>

<style scoped>
#container {
  width: 100%;
  height: 6rem;
}
</style>
